package com.happyscan138.makefun.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.os.Looper;

import com.happyscan138.makefun.Chat;
import com.happyscan138.makefun.R;
import com.happyscan138.makefun.Urls.Urls;
import com.happyscan138.makefun.base.Notice;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

import static com.happyscan138.makefun.base.http.client;
import static com.loopj.android.http.AsyncHttpClient.log;

;

/**
 * Created by Administrator on 2017/3/29.
 */

public class PollingService extends Service {
    public static final String ACTION = "com.happyscan138.makefun.service.PollingService";
    private Notification mNotification;
    private NotificationManager mManager;
    private SharedPreferences preferences;
    private String access_key;
    private RequestParams params;
    private List<Notice> listData;
    private Notice mData;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        preferences=getSharedPreferences("UserInfo",MODE_PRIVATE);
        access_key=preferences.getString("UserId","");
        params=new RequestParams();
        params.put("access_key",access_key);
        initNotifiManager();
    }

    @Override
    public void onStart(Intent intent, int startId) {
       new PollingThread().start();
    }
    //初始化通知栏配置
    private void initNotifiManager() {
        mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        int icon = R.mipmap.ic_launcher;
        mNotification = new Notification();
        mNotification.icon = icon;
        mNotification.tickerText = "New Message";
        mNotification.defaults |= Notification.DEFAULT_SOUND;
        mNotification.flags = Notification.FLAG_AUTO_CANCEL;
    }
    //弹出Notification
    private void showNotification() {


            for (Notice notice:listData) {
                Notification.Builder builder1 = new Notification.Builder(this);
                builder1.setSmallIcon(R.mipmap.icon); //设置图标
                //builder1.setTicker();
                builder1.setContentTitle(notice.title); //设置标题
                log.e("servicetitle",notice.title);
                builder1.setContentText(notice.context); //消息内容
                builder1.setWhen(System.currentTimeMillis()); //发送时间
                builder1.setDefaults(Notification.DEFAULT_ALL); //设置默认的提示音，振动方式，灯光
                builder1.setAutoCancel(true);//打开程序后图标消失
                Intent intent = new Intent();
                intent.putExtra("user_id", mData.user_id);
                log.e("Makeservice",mData.user_id);
                intent.setClass(this, Chat.class);
                PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

                builder1.setContentIntent(pendingIntent);
                Notification notification1 = builder1.build();
                mManager.notify(listData.size(), notification1); // 通过通知管理器发送通知
            }





    }
    /**
     * Polling thread
     * 模拟向Server轮询的异步线程
     * @Author Ryan
     * @Create 2013-7-13 上午10:18:34
     */
    int count = 0;
    class PollingThread extends Thread {

        public void run() {
            Looper.prepare();
            log.e("Makeservice","polling");
            count ++;
            //当计数能被5整除时弹出通知
            if (count % 5 == 0) {

                listData =new ArrayList<>();
                client.post(Urls.MessageNotice, params,new JsonHttpResponseHandler(){
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        String jsonStr=response.toString();
                        log.e("Makeservice",jsonStr);
                        try {
                            JSONObject data=new JSONObject(jsonStr);
                            JSONArray jsonArrayData=data.getJSONArray("data");
                            for (int i=0;i<jsonArrayData.length();i++){
                                JSONObject jsonObjectData=jsonArrayData.getJSONObject(i);
                                mData=new Notice();
                                mData.title=jsonObjectData.getString("nick_name");
                                mData.context="您有新的私信";
                                mData.user_id=jsonObjectData.getString("send_u_id");
                                listData.add(mData);

                                int Tag_read=jsonObjectData.getInt("is_tips");
                                if(Tag_read==0){
                                    showNotification();
                                    continue;
                                }
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                        super.onFailure(statusCode, headers, responseString, throwable);
                        log.e("service","fail");
                    }
                });

            }
            Looper.loop();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
       log.e("service","Service:onDestroy");
    }
}
